<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            padding:0;
            margin: 0;
        }
        html,body, #app{
            width: 100%;
            height: 100%;
            overflow: hidden;
        }
        #app{
            background: url('./zhibo.png');
            background-size: cover;
        }
        #move{
            width: 150px;
            height: 200px;
            background: rgb(197, 89, 89);
            position: absolute;
            transition: left 0.3s;
        }
    </style>
</head>
<body>
    <div id="app">
        <div id="move"></div>
    </div>

    <script>
        //获取元素
        let move = document.querySelector("#move");
        let app = document.querySelector("#app");

        app.addEventListener('touchstart', function(e){
            e.preventDefault();
        })


        move.addEventListener('touchstart', function(e){
            //获取 move 元素距离左侧的偏移量
            this.l = move.offsetLeft;
            //获取手指按下时, 手指距离左侧的偏移量
            this.x = e.changedTouches[0].clientX;

            this.t = move.offsetTop;
            this.y = e.changedTouches[0].clientY;
            //移除过渡样式
            move.style.transition = 'none';
        });
        move.addEventListener('touchmove', function(e){
            //获取移动后, 手指距离左侧的偏移量
            let _x = e.changedTouches[0].clientX;
            //计算新的 left 的值
            let newLeft = _x - (this.x - this.l);

            let _y = e.changedTouches[0].clientY;
            let newTop = _y - (this.y - this.t);
            //设置
            move.style.left = newLeft + 'px';
            move.style.top = newTop + 'px';
        });

        move.addEventListener('touchend', function(){
            move.style.transition = 'left 0.3s';
            //自动吸附的效果
            let middle = (app.offsetWidth - move.offsetWidth) / 2;
            let maxLeft = app.offsetWidth - move.offsetWidth;
            //获取当前时刻, move 元素的 left 的值
            let left = move.offsetLeft;
            let newLeft;
            //判断
            if(left <= middle){
                //向左吸附
                newLeft = 0;
            }else{
                newLeft = maxLeft;
            }
            //设置
            move.style.left = newLeft + 'px';
        });

    </script>
</body>
</html>